//
//  PaperModel.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/3/6.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
import ObjectMapper

///试卷状态
enum PaperStatus: Int {
    case unknow = 0
    ///试用
    case trial = 1
    ///已购买
    case bought = 2
    ///免费
    case free = 3
    
    ///收藏
    case likes
    
    ///错题列表
    case errorItems
    
    ///答题记录
    case record
    
    ///解析
    case analysis
    
    ///主观题自评分
    case selfReported
}

///做题模式
enum PaperMethod: Int {
    ///练习 （答题、看解析，不能交卷）
    case exercise = 1
    ///考试 （答题、交卷、不能看解析）
    case exam = 2
}

///试卷
class PaperModel: Mappable {
    ///试卷id
    var paperId: Int?
    var title: String?
    ///用户试卷关联id，做题提交的时候请提交该id
    var pUserSummaryId: Int?
    ///题目列表
    var paperItems: [PaperItemModel]?
    ///题目数量
    var itemTotal: Int?
    ///做题模式
    var method: PaperMethod?
    ///购买状态
    var status: PaperStatus?
    var price: Int?
    
    ///单选题得分
    var singleChoiceScore: Double?
    ///多选题得分
    var multiChoiceScore: Double?
    ///判断题得分
    var trueOrFalseScore: Double?
    ///简答题得分
    var shortAnswerScore: Double?
    ///综合分析题总得分
    var analysisQuestScore: Double?
    ///公文筐检测题总得分
    var officialDocScore: Double?
    ///计算题总得分
    var calcQuestScore: Double?
    ///总得分
    var totalScore: Double?
    ///考试用时
    var timeInterval: TimeInterval?
    
    func mapping(map: Map) {
        paperId <- map["paperId"]
        title <- map["title"]
        pUserSummaryId <- map["pUserSummaryId"]
        paperItems   <- map["paperItems"]
        itemTotal  <- map["itemTotal"]
        method  <- map["method"]
        status  <- map["status"]
        price  <- map["price"]
        
        singleChoiceScore <- map["singleChoiceScore"]
        multiChoiceScore <- map["multiChoiceScore"]
        trueOrFalseScore <- map["trueOrFalseScore"]
        shortAnswerScore <- map["shortAnswerScore"]
        analysisQuestScore <- map["analysisQuestScore"]
        officialDocScore <- map["officialDocScore"]
        calcQuestScore <- map["calcQuestScore"]
        totalScore <- map["totalScore"]
        
        timeInterval <- map["timeConsume"]
    }
    
    required init?(map :Map) { }
    
    required init() { }
    
    ///根据交卷接口返回的数据，更新paper
    func updateFromResultPaper(_ resultPaper: PaperModel) -> PaperModel {
        self.paperItems = resultPaper.paperItems
        self.shortAnswerScore = resultPaper.shortAnswerScore
        self.singleChoiceScore = resultPaper.singleChoiceScore
        self.multiChoiceScore = resultPaper.multiChoiceScore
        self.trueOrFalseScore = resultPaper.trueOrFalseScore
        self.shortAnswerScore = resultPaper.shortAnswerScore
        self.analysisQuestScore = resultPaper.analysisQuestScore
        self.officialDocScore = resultPaper.officialDocScore
        self.calcQuestScore = resultPaper.calcQuestScore
        
        self.totalScore = resultPaper.totalScore
        self.timeInterval = resultPaper.timeInterval
        
        
        self.method = PaperMethod.exercise
        //将题目设置为解析模式
        if let items = self.paperItems {
            for item in items {
                item.method = .analysis
            }
        }
        
        return self
    }
    
    ///获取错题试卷,返回新的Paper对象
    func paperForErrorAnalysis() -> PaperModel {
        let newPaper = PaperModel()
        newPaper.paperId = paperId
        newPaper.title = title
        newPaper.pUserSummaryId = pUserSummaryId
        newPaper.method = method
        newPaper.price = price
        newPaper.status = status
        newPaper.singleChoiceScore = singleChoiceScore
        newPaper.multiChoiceScore = multiChoiceScore
        newPaper.trueOrFalseScore = trueOrFalseScore
        newPaper.shortAnswerScore = shortAnswerScore
        newPaper.analysisQuestScore = analysisQuestScore
        newPaper.officialDocScore = officialDocScore
        newPaper.calcQuestScore = calcQuestScore
        newPaper.totalScore = totalScore
        
        if let paperItems = self.paperItems  {
            var resultItems = [PaperItemModel]()
            for item in paperItems {
                if item.userAnswerResult != .correct {
                    item.method = .analysis
                    resultItems.append(item)
                }
            }
            newPaper.paperItems = resultItems
        }
        
        return newPaper
    }
    
    ///获取所有试卷,返回新的Paper对象
    func paperForAllAnalysis() -> PaperModel {
        let newPaper = PaperModel()
        newPaper.paperId = paperId
        newPaper.title = title
        newPaper.pUserSummaryId = pUserSummaryId
        newPaper.method = method
        newPaper.price = price
        newPaper.status = status
        newPaper.singleChoiceScore = singleChoiceScore
        newPaper.multiChoiceScore = multiChoiceScore
        newPaper.trueOrFalseScore = trueOrFalseScore
        newPaper.shortAnswerScore = shortAnswerScore
        newPaper.analysisQuestScore = analysisQuestScore
        newPaper.officialDocScore = officialDocScore
        newPaper.calcQuestScore = calcQuestScore
        newPaper.totalScore = totalScore
        
        if let paperItems = self.paperItems  {
            for item in paperItems {
                item.method = .analysis
            }
            newPaper.paperItems = paperItems
        }
        
        return newPaper
    }
    
    ///获取已做简答题试卷，返回新的Paper对象
    func paperForSelfReport() -> PaperModel {
        let newPaper = PaperModel()
        newPaper.paperId = paperId
        newPaper.title = title
        newPaper.pUserSummaryId = pUserSummaryId
        newPaper.method = method
        newPaper.price = price
        newPaper.status = status
        newPaper.singleChoiceScore = singleChoiceScore
        newPaper.multiChoiceScore = multiChoiceScore
        newPaper.trueOrFalseScore = trueOrFalseScore
        newPaper.shortAnswerScore = shortAnswerScore
        newPaper.analysisQuestScore = analysisQuestScore
        newPaper.officialDocScore = officialDocScore
        newPaper.calcQuestScore = calcQuestScore
        newPaper.totalScore = totalScore
        
        if let paperItems = self.paperItems  {
            var resultItems = [PaperItemModel]()
            for item in paperItems {
                ///主观题
                if item.type?.isSubjective() == true {
                    //有答案
                    if  String.lsf_hasValue(item.userAnswer) {
                        item.method = .selfReported
                        resultItems.append(item)
                    }
                }
            }
            newPaper.paperItems = resultItems
        }
        
        return newPaper
    }
    
    ///计算自评分总分
    func calculateSelfReportScore() {
        
        let paper = paperForSelfReport()
        
        guard let paperItems = paper.paperItems else { return }
        
        var score: Double = 0
        
        var shortAnswerScore: Double = 0
        var analysisQuestScore: Double = 0
        var officialDocScore: Double = 0
        var calcQuestScore: Double = 0
        
        for item in paperItems {
            
            if item.type == PaperItemType.shortAnswer {
                shortAnswerScore += item.userScore ?? 0
            }
            else if item.type == PaperItemType.analysis {
                analysisQuestScore += item.userScore ?? 0
            }
            
            else if item.type == PaperItemType.in_trayTest {
                officialDocScore += item.userScore ?? 0
            }
            
            else if item.type == PaperItemType.calculation {
                calcQuestScore += item.userScore ?? 0
            }
            score += item.userScore ?? 0
        }
        
        self.shortAnswerScore = shortAnswerScore
        self.analysisQuestScore = analysisQuestScore
        self.officialDocScore = officialDocScore
        self.calcQuestScore = calcQuestScore
        
        self.totalScore = (self.totalScore ?? 0) + score
    }
    
    ///获取指定类型题目列表
    func paperItemsFor(_ type: PaperItemType) -> [PaperItemModel]? {
        guard let paperItems = self.paperItems else { return nil }
        
        var resultItems = [PaperItemModel]()
        for item in paperItems {
            if item.type == type {
                resultItems.append(item)
            }
        }
        return resultItems
    }
    
    ///更新试题的模式
    func updatePaperItemMethod(_ status: PaperStatus) {
        guard let items = self.paperItems else { return }
        
        var method = PaperItemMethod.exam
        switch status {
        case .analysis, .record:
            method = .analysis
            
        case .selfReported:
            method = .selfReported

        default:
            method = .exam
        }
        
        for item in items {
            item.method = method
        }
    }
}





